<?php
namespace app\service;
use think\facade\Db;
use app\model\InvoicesModel;
use app\model\InInvoicesModel;
use Exception;
use app\model\SingleModel;
use app\model\SaleModel;
use app\model\SaleIncomeModel;
use app\model\SaleOutlayModel;
use app\model\ClientModel;
use app\model\SupplierModel;

class InvoicesService{  

    public function searchBySn($params){       
        $params['sn'] = trim($params['sn']);
        $saleModel = new SaleModel();
        $res = $saleModel->where('sn',$params['sn'])->find();
        if($res){
            $saleIncomeModel = new SaleIncomeModel();
            $data = $saleIncomeModel->where(['type'=>$res['type'],'pid'=>$res['id']])->select();  
            $list=[];
            foreach ($data as $v) {
                $totalmoney= $v['num']* $v['sell_price'];
                $invoicesModel = new InInvoicesModel();
                $invoices_data = $invoicesModel->where(["income_id"=>$v["id"],"type"=>$v['type']])->select();
                $invoices = 0;
                foreach ($invoices_data as $x) {
                    $invoices += $x['invoice_price'];
                }               
                $client = new ClientModel();
                $clientinfo = $client->where('id',$v['client_id'])->find();
                $temp=[
                    'producttype'=>'sale',
                    'sn'=>$res['sn'],
                    'title'=>$res['title'],
                    'type'=>$v['type'],
                    'id' => $v['id'],
                    'pid' => $res['id'],                  
                    'client' => $clientinfo?$clientinfo['company_name']:'',
                    'num'=>$v['num'],
                    'totalmoney'=>$totalmoney,                    
                    'invoiced'=>$invoices,
                    'uninvoiced'=>$totalmoney-$invoices
                ]; 
                array_push($list,$temp);
            } 
                 
            return $list;
        }
        $singleModel = new SingleModel();
        $data = $singleModel->where('sn',$params['sn'])->select();
        if($data){           
            $list=[];
            foreach ($data as $v) {
                $totalmoney= $v['num']* $v['sell_price'];
                $invoicesModel = new InInvoicesModel();
                $invoices_data = $invoicesModel->where(["income_id"=>$v["id"],"type"=>$v['type']])->select();
                $invoices = 0;
                foreach ($invoices_data as $x) {
                    $invoices += $x['invoice_price'];
                }              
                $client = new ClientModel();
                $clientinfo = $client->where('id',$v['client_id'])->find();
                $temp=[
                    'producttype'=>'single',
                    'sn'=>$v['sn'],
                    'title'=>$v['content'],
                    'type'=>$v['type'],
                    'id' => $v['id'],
                    'parentid' => $v['id'],                  
                    'client' => $clientinfo?$clientinfo['company_name']:'',
                    'num'=>$v['num'],
                    'totalmoney'=>$totalmoney,                    
                    'invoiced'=>$invoices,
                    'uninvoiced'=>$totalmoney-$invoices
                ]; 
                array_push($list,$temp);
            }   
            return $list;
        }   
        return [];     
    } 

    public function searchByKeyword($params){       
        $params['keyword'] = trim($params['keyword']);
        $where[] = ['company_name','like',"%{$params['keyword']}%"]; 
        $data = InvoicesModel::where($where)->order('id','desc')->select(); 
        return $data;     
    } 
    
    public function list($params){
        $where=[];
        $page = $params['page'];
        $pageCount = $params['page_count'];
        if(!empty($params['keyword'])){
            $where[] = ['company_name|mechanism_code|invoice_content','like',"%{$params['keyword']}%"];   
        }
        if(!empty($params['money'])){
            $where[] = ['receipt_amount','=',$params['money']];   
        }
        if(!empty($params['is_receive']) && $params['is_receive']=="true"){
            $where[] = ['receipt_date','<>',''];      
        }
        $data = InvoicesModel::alias('a')
            ->field('a.*,b.cn_name as operator')
            ->join('user b','a.operator_id=b.id','left')
            ->where($where)->page($page,$pageCount)->order('id','desc')->select(); 
        $count = InvoicesModel::where($where)->count();      
        return ["list"=>$data,"count"=>$count];
    } 
    
    public function info($id){
        $invoicess = InvoicesModel::where('id',$id)->select(); 
        return $invoicess;
    }

    public function save($params){              
        if(empty($params['id'])){     
            $params['datas'] = json_encode($params['datas'],JSON_UNESCAPED_UNICODE);      
            $data = InvoicesModel::create($params); 
        }else{
            $data = InvoicesModel::update($params, ['id' => $params['id']]); 
        }        
        return $data;
    }

    public function delete($params){   
        $data = InvoicesModel::destroy($params['id']);         
        return $data;
    }

    public function review($params){  
        $id = $params['id'];     
        $invoice_no = $params['invoice_no'];    
        $invoice_date = $params['invoice_date']; 

        $old = InvoicesModel::where('id',$id)->find();      
        $new=InvoicesModel::where('id',$id)->update(['is_review'=>'1','isread'=>1]); 
        if($new){
            $list = json_decode($old['datas'],true);  
            foreach($list as $v){
                $temp = [
                    "invoice_date"=>$invoice_date,
                    "invoice_no"=>$invoice_no,
                    "inout"=>0,
                    "type"=>$v['type'],
                    "income_id"=>$v['id'],
                    "company_name"=>$old['company_name'],
                    "invoice_content"=>$old['invoice_content'],
                    "invoice_price"=>$v['realmoney'],
                    "operator_id"=>$params['operator_id'],
                    "invoice_id"=>$old['id'],
                    "is_check"=>1
                ];
                $data = InInvoicesModel::create($temp);              
            }    
        }
        return $new;
    }

    //支出取消审核
    public function cancel_review($id){
        $old = InvoicesModel::where('id',$id)->find();
        $data=InvoicesModel::where('id',$id)->update(['is_review'=>'0']);  
        if($data){           
            $data = IninvoicesModel::where('invoice_id',$id)->delete();  
        }
        return $data;
    }
}